<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="模具">
          <el-select
            style="width: 100%"
            v-model="searchParam.assetId"
            placeholder="请选择模具"
            filterable
            :filter-method="customMouldFilter"
            clearable
          >
            <el-option
              v-for="item in filteredMouldList"
              :key="item.id"
              :label="item.assetCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            style="width: 100%"
            v-model="searchParam.status"
            placeholder="请选择状态"
            filterable
            clearable
          >
            <el-option
              v-for="item in statusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="位置">
          <el-tree-select
            placeholder="请选择位置"
            filterable
            v-model="searchParam.locationId"
            :data="locationInfoTree"
            node-key="id"
            clearable
            :props="{ label: 'locationName', children: 'nodes' }"
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="模具类型">
          <el-tree-select
            placeholder="请选择模具类型"
            v-model="searchParam.assetTypeId"
            :data="catalogList"
            :render-after-expand="false"
            :check-strictly="true"
            node-key="id"
            :props="{
              label: 'assetTypeName',
              value: 'id',
              children: 'nodes',
            }"
            clearable
          />
        </el-form-item>
        <el-form-item label="登记时间">
          <el-date-picker
            v-model="searchParam.registrationTimeSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getregistrationTime"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          label="模具编码"
          prop="assetCode"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="阶段"
          prop="sendStage"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="模具名称"
          prop="assetName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="位置"
          prop="locationName"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="模具类型"
          prop="assetTypeName"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="累计寿命"
          prop="cumulativeUseTimes"
          min-width="100"
          show-overflow-tooltip
          align="right"
          header-align="center"
        />
        <el-table-column
          label="模具寿命"
          prop="assetLifespan"
          min-width="100"
          show-overflow-tooltip
          align="right"
          header-align="center"
        />
        <el-table-column
          label="登记时间"
          prop="registrationTime"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="状态"
          prop="status"
          min-width="60"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <span v-if="scope.row.status == 2">已关闭</span>
            <span v-else-if="scope.row.status == 3">不合格</span>
            <span v-else>未判定</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              v-if="scope.row.status == 2"
              @click="openDialogEdit2(scope.row)"
              ><i-ep-search />
              附件
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              v-else
              @click="openDialogEdit(scope.row)"
              ><i-ep-edit />
              判定
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <eammouldemailrecord-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />

    <eammouldemailrecordfile2-edit
      :visible="editDialog.visible"
      :title="editDialog.title"
      :data="editDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="editDialog.readvisible"
      @change-visible="changeVisibleEdit"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { debounce } from "lodash-es";

defineOptions({
  name: "EAMMOLDEAMMOULDEMAILRECORD2",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/eam/eammouldemailrecord/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  roleType: 2,
  sendType: 1,
  assetId: "",
  statusList: [1, 2, 3],
  locationId: "",
  assetTypeId: "",
  registrationTimeSearch: [],
  registrationTimeStart: "",
  registrationTimeEnd: "",
};

const deleteParam = {
  api: "/eam/eammouldemailrecord/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
  getCAtalogList();
  getLocationInfoTree();
  getMouldList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

const editDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/eam/eammouldemailrecord/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开模具寿命邮件发送记录主表表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改模具寿命邮件发送记录";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增模具寿命邮件发送记录";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}
/** 打开模具寿命邮件发送记录主表表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "模具寿命邮件发送记录详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getregistrationTime(data: any) {
  if (data) {
    searchParam.value.registrationTimeStart = data[0];
    searchParam.value.registrationTimeEnd = data[1];
  } else {
    searchParam.value.registrationTimeStart = "";
    searchParam.value.registrationTimeEnd = "";
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/eam/eammouldemailrecord/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}
// 获取模具类型树数据
const catalogList: any = ref([]);
const getCAtalogList = async () => {
  // 获取内容树
  await request({
    url: "eam/mouldAssetType/getAvailableTree",
    method: "POST",
    data: { assetKind: "3" },
  }).then((res) => {
    catalogList.value = res.data;
  });
};
// 获取位置信息下拉树
const locationInfoTree = ref([]);
const getLocationInfoTree = async () => {
  const { data } = await request({
    url: "/eam/locationInfo/getTree",
    method: "POST",
    data: {
      enabled: 1,
    },
  });
  locationInfoTree.value = data;
};

const mouldList = ref([]);
const filteredMouldList = ref([]);
async function getMouldList() {
  const { data } = await request({
    url: "/eam/mouldAssetInfo/getList",
    method: "post",
    data: {},
  });
  mouldList.value = data;
  filteredMouldList.value = [...data];
}
const customMouldFilter = debounce((query: any) => {
  if (!query) {
    filteredMouldList.value = [...mouldList.value];
    return;
  }
  filteredMouldList.value = mouldList.value.filter((option: any) =>
    option.assetCode.toLowerCase().includes(query.toLowerCase())
  );
}, 300);

function openDialogEdit(row: any) {
  editDialog.title = "工单详情";
  getInfoEdit(row.id);
  editDialog.readvisible = false;
}
function openDialogEdit2(row: any) {
  editDialog.title = "工单详情";
  getInfoEdit(row.id);
  editDialog.readvisible = true;
}

async function getInfoEdit(id: string) {
  request({
    url: `/eam/eammouldemailrecord/getDetail/${id}`,
    method: "get",
  })
    .then((data) => {
      editDialog.data = data.data;
      editDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

function changeVisibleEdit(value: boolean) {
  editDialog.visible = value;
  if (!value) {
    editDialog.data = {};
  }
}

const statusList = [
  { label: "未判定", value: 1 },
  { label: "已关闭", value: 2 },
  { label: "不合格", value: 3 },
];
</script>
